package org.example.utils;

import lombok.extern.slf4j.Slf4j;
import org.example.common.AdminSessionBean;
import org.example.common.BusinessCode;
import org.example.common.BusinessException;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * 后台用户信息获取
 *
 * @author fuchangshun
 * @date 2023/2/9 17:10
 */
@Slf4j
public class AdminSessionHolder {

    /**
     * 获取SessionBean
     *
     * @return SessionBean
     */
    public static AdminSessionBean getSessionBean() {
        //从Header中获取用户信息
        ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        if (null == servletRequestAttributes) {
            log.error("暂无ServletRequestAttributes信息");
            throw new BusinessException(BusinessCode.FATAL);
        }
        HttpServletRequest request = servletRequestAttributes.getRequest();
        Object sessionUser = request.getAttribute("sessionUser");
        if (null == sessionUser) {
            //请不要在未经过网关登录校验的位置获取用户信息;
            log.error("请求头暂无用户信息");
            throw new BusinessException(BusinessCode.ERROR_RISK);
        }
        if (!(sessionUser instanceof AdminSessionBean)) {
            log.error("sessionUser不是CooperatorSessionBean类型");
            throw new BusinessException(BusinessCode.ERROR_RISK);
        }
        return (AdminSessionBean) sessionUser;
    }

}
